#!/bin/bash -eu
#
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Grab the available memory on the server, we divide by 4096 because we want
# to convert it to bytes and 25% of the available memory.

declare -i available_memory
declare -i memory_for_redis

available_memory=$(awk '/MemAvailable/ { print int($2) }' /proc/meminfo)
memory_for_redis=$((available_memory / 4096))

# Ensures redis has at least 20 MB avalable but does not use over 400 MB
if (( "${memory_for_redis}" < 20 )); then
  memory_for_redis=20;
elif (( "${memory_for_redis}" > 400 )); then
  memory_for_redis=400;
fi

echo "maxmemory ${memory_for_redis}mb" >> /etc/redis/redis.conf
systemctl restart redis

# Configure env.php to use redis as a backend cache

php << 'EOPHP' > /tmp/env.php
<?php
$config = require('/var/www/html/app/etc/env.php');
$config['cache'] = array(
  'frontend' => array(
    'default' => array(
      'backend' => 'Cm_Cache_Backend_Redis',
      'backend_options' => array(
        'server' => '127.0.0.1',
        'database' => 0,
        'port' => 6379),
    ),
    'page_cache' => array(
      'backend' => 'Cm_Cache_Backend_Redis',
      'backend_options' => array(
        'server' => '127.0.0.1',
        'port' => 6379,
        'database' => 1,
        'compress_data' => 0))));
echo "<?php\nreturn " . var_export($config, true) . ";\n";
EOPHP

# Due to the file locking in linux, we save the output to a tmp file then save.
mv /tmp/env.php /var/www/html/app/etc/env.php
chown www-data:www-data /var/www/html/app/etc/env.php
